import axios from 'axios';
import {INTERACE_SAAS_ORDER_BASE_URL} from 'components/api/index-local';
import {
  setSessionStorageItem,
  getSessionStorageItem,
  getClientType,
  getLocalStorageItem,
  setLocalStorageItem
} from 'components/api/utils';
import {getUserIdentity} from 'components/api/interface-hhy';
import {BUSINESS_TYPE_TS, BUSINESS_TYPE_MC, BUSINESS_TYPE_ZT, BUSINESS_TYPE_WS} from 'components/api/interface-saas';
// @todo 测试使用
// axios.interceptors.response.use(res => {
//   return res.data;
// }, err => {
//   console.log(err);
//   return (new Promise()).reject(err);
// });

/**
 * 订单支付状态 SUCCESS,WAITING,FAIL，CHECKING
 * WAITING|FAIL且剩余时间>0,可以进行支付操作
  */
export const ORDER_PAY_SUCCESS = 'SUCCESS';
export const ORDER_PAY_WAITING = 'WAITING';
export const ORDER_PAY_FAIL = 'FAIL';
export const ORDER_PAY_CHECKING = 'CHECKING';

/*
 * 未接单（交易创建等待商家接单）WAIT_RECEIVE_ORDER
 * 商家已经接单BRANCH_RECEIVED_ORDER
 * 商家取消订单BRANCH_CANCELED_ORDER
 * 订单完成ORDER_FINISHED
 * 订单制作中ORDER_MAKEING,
 * PAY_TIMEOUT:因为支付超时而取消
 */
export const ORDER_STATUS_WAIT_RECEIVE_ORDER = 'WAIT_RECEIVE_ORDER';
export const ORDER_STATUS_BRANCH_RECEIVED_ORDER = 'BRANCH_RECEIVED_ORDER';
export const ORDER_STATUS_BRANCH_CANCELED_ORDER = 'BRANCH_CANCELED_ORDER';
export const ORDER_STATUS_ORDER_FINISHED = 'ORDER_FINISHED';
export const ORDER_STATUS_ORDER_MAKEING = 'ORDER_MAKEING';
export const ORDER_STATUS_ORDER_MAKING = 'ORDER_MAKEING';
export const ORDER_STATUS_PAY_TIMEOUT = 'PAY_TIMEOUT';

// 优惠 SCORE积分 COUPON卡券
export const DISCOUNT_SCORE = 'SCORE';
export const DISCOUNT_COUPON = 'COUPON';
export const DISCOUNT_MAP = {
  [DISCOUNT_SCORE]: '积分',
  [DISCOUNT_COUPON]: '抵用券'
};

// 支付方式：ALIPAY支付宝，WECHAT 微信，CARDPAY好会员支付
export const PAY_TYPE_ALIPAY = 'ALIPAY';
export const PAY_TYPE_WECHAT = 'WECHAT';
export const PAY_TYPE_CARDPAY = 'CARDPAY';
export const PAY_TYPE_MAP = {
  [PAY_TYPE_ALIPAY]: '支付宝支付',
  [PAY_TYPE_WECHAT]: '微信支付',
  [PAY_TYPE_CARDPAY]: '好会员支付'
};

/**
 * 订单状态
 * @param {String} payStatus
 * @param {String} status
 */
export function orderStatus(payStatus, status) {
  if (status === ORDER_STATUS_PAY_TIMEOUT) {
    return '订单关闭';
  }

  switch (payStatus) {
    case ORDER_PAY_WAITING:
      return '等待支付';
    case ORDER_PAY_FAIL:
      return '支付失败';
    case ORDER_PAY_CHECKING:
      return '支付正在确认';
    case ORDER_PAY_SUCCESS:
      return '订单完成';
  }
  return ' ';
}
/**
 * 订单描述
 * @param {String} payStatus
 * @param {String} status
 */
export function orderDescription(payStatus, status) {
  if (status === ORDER_STATUS_PAY_TIMEOUT) {
    return '超过支付时间未支付';
  }

  switch (payStatus) {
    case ORDER_PAY_WAITING:
    case ORDER_PAY_FAIL:
      return '订单未支付，订单将自动取消';
    case ORDER_PAY_CHECKING:
      return '支付正在处理，请稍后确认';
    case ORDER_PAY_SUCCESS:
      return '感谢您的信任，期待再次光临';
  }
  return ' ';
}

/**
 * 订单支付方式
 * @param {String} payStatus
 * @param {String} payType
 */
export function orderPayType(payStatus, payType) {
  if (payStatus !== ORDER_PAY_SUCCESS) {
    return '尚未支付';
  }
  return PAY_TYPE_MAP[payType] ? PAY_TYPE_MAP[payType] : '';
}

/**
 * 判断订单是否可支付
 * @param order
 * @return {boolean}
 */
export function orderCanPay(order) {
  return order.timeLeft > 0 &&
    order.status !== ORDER_STATUS_PAY_TIMEOUT &&
    (order.payStatus === ORDER_PAY_WAITING || order.payStatus === ORDER_PAY_FAIL);
}

/**
 * 判断订单是否可【再来一单】
 * @param order
 * @return {boolean}
 */
export function orderCanCopy (order) {
  return order.businessType !== BUSINESS_TYPE_TS && order.payStatus === ORDER_PAY_SUCCESS;
}

/**
 * 创建axios实例
 * @return {axios}
 */
export function createHttp() {
  let $httpSaas = axios.create({
    baseURL: INTERACE_SAAS_ORDER_BASE_URL,
    headers: {'Content-Type': 'application/json;charset=UTF-8'},
    timeout: 5000
  });
// 添加一个响应拦截器
  $httpSaas.interceptors.response.use(res => {
    return res.data;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });
  return $httpSaas;
}

/**
 * 获取接口错误信息
 * @param error
 * @param defaultMessage
 * @return {String}
 */
export function getErrorMessage(error, defaultMessage = '操作失败') {
  let response = error.response;
  if (!response) {
    return defaultMessage;
  }
  return response.data ? (response.data.message ? response.data.message : defaultMessage) : defaultMessage;
}

/**
 * 创建订单  @todo 是否需要传入金额待确认
 * @param params
 */
export function orderCreate(params) {
  let userIdentity = getUserIdentity();
  let url = '/order';
  let {
    mobile,
    persons = 1,
    note = '',
    arriveTime = 0,
    personNum = 0,
    receiver = '',
    deliverAddress = '',
    foodList = [],
    discountlist = []
  } = params;
  let newParams = {
    branchId: userIdentity.branchId,
    orderChannel: getClientType(),
    mobile: mobile,
    orderType: userIdentity.businessType,
    persons: persons,
    orderUser: userIdentity.userId,
    note: note,
    tableId: userIdentity.tableId,
    arriveTime: arriveTime,
    personNum: personNum,
    receiver: receiver,
    deliverAddress: deliverAddress,
    customerLevel: userIdentity.levelType,
    foodList: foodList,
    discountList: discountlist,
    orgId: userIdentity.orgId,
    uid: userIdentity.uid
  };
  let $httpSaas = createHttp();
  return $httpSaas.post(url, newParams, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
}

// @todo 接口待定
/**
 * GET /v1/branch/{branchId}/order/{orderId}
 * 查询订单详情
 * @param orderId
 * @param branchId
 * @return {Promise}
 */
export function getOrderDetail(orderId, branchId = 0) {
  let userIdentity = getUserIdentity();
  !branchId && (branchId = userIdentity.branchId);
  let url = '/branch/' + branchId + '/order/' + orderId;
  let $httpSaas = createHttp();
  return $httpSaas.get(url);

  /**
   * 测试使用
   * return axios.get('static/test/order' + orderId + '.json');
   */
}

// @todo 接口待定
/**
 * GET /v1/org-id/{orgId}/order-user/{orderUserId}/order/{beginDay}/{endDay}
 * @param page 第几页
 * @return {Promise}
 */
export function getOrderList(page = 1) {
  let beginDay = 90 * (page - 1);
  let endDay = 90 * page;
  let userIdentity = getUserIdentity();
  let url = '/org-id/' + userIdentity.orgId +
    '/order-user/' + userIdentity.userId +
    '/order/' + beginDay +
    '/' + endDay;
  let $httpSaas = createHttp();
  return $httpSaas.get(url);

  // 测试使用
  // return axios.get('static/test/orders.json');
}

/**
 * 订单支付
 * 如果是微信和支付宝支付，服务器生成统一下单结果后告知客户端，客户端调起JSAPI，支付成功后跳转支付结果页面并通知saas支付结果
 * 如果是好会员支付，服务器直接调起好会员接口处理卡券、积分、储值卡消费
 * @author ytl
 * @param params
 * @return {Promise}
 * todo 接口待定
 */
export function orderPay(params) {
  let userIdentity = getUserIdentity();
  let {orderId, payType} = params;
  let url = '/payment';
  let $httpSaas = createHttp();
  return $httpSaas.post(url, {
    uid: userIdentity.uid,
    authId: userIdentity.authId,
    branchId: userIdentity.branchId,
    orderId: orderId,
    orgId: userIdentity.orgId,
    payType: payType,
    payUser: userIdentity.userId
  });
}

/**
 * 微信/支付宝JSAPI支付成功后通知saas支付结果
 * post payment-notify
 * @param {String} outTradeNo 支付宝/微信统一下单的外部交易号
 * @return {Promise}
 */
export function orderPayNotify (outTradeNo) {
  let userIdentity = getUserIdentity();
  let url = '/payment-notify';
  let $http = createHttp();
  return $http.post(url, {
    branchId: userIdentity.branchId,
    orgId: userIdentity.orgId,
    outTradeNo: outTradeNo
  });
}
